php数组和网址URL参数的互相转换 | 您所在的位置:网站首页 › php 转字符串 › php数组和网址URL参数的互相转换 |
前言
接口调试和开发的过程中,相信很多小伙伴都会经常用到数组和url参数的相互转换来模拟请求。其实不用自己再通过foreach或implode之类的手动实现,php自身的函数库给我们提供了两个方法,完全够用: 一、http_build_query将数据转换为URL参数格式,返回一个 URL 编码后的字符串。 示例: $arr = [ 'name' => 'ngxcode', 'url' => 'https://www.ngxcode.com', 'flowid' => '1001035', 'desc' => 'php share' ]; echo http_build_query($arr) . "\n"; echo http_build_query($arr, '', ';');输出: name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share name=ngxcode;url=https%3A%2F%2Fwww.ngxcode.com;flowid=1001035;desc=php+share 二、parse_strURL参数字符串转为数组,将字符串解析成多个变量 示例: $url_params = 'name=ngxcode&url=https%3A%2F%2Fwww.ngxcode.com&flowid=1001035&desc=php+share'; //如果设置了第二个变量 result,变量将会以数组元素的形式存入到这个数组,作为替代。 parse_str($url_params, $result); print_r($result);输出 Array ( [name] => ngxcode [url] => https://www.ngxcode.com [flowid] => 1001035 [desc] => php share ) PHP官方文档以下为两个函数的官方文档介绍,需要更复杂转换和解析需求的,可查看文档使用 https://www.php.net/manual/zh/function.http-build-query.php https://www.php.net/manual/zh/function.parse-str.php 原文地址:https://www.ngxcode.com/archives/519.html |
CopyRight 2018-2019 实验室设备网 版权所有 |